﻿using AutoMapper;
using MediatR;
using Production.CommonLib.Models;
using Production.DomainLib.AggregatesModel.ProcessAggregate;
using Swimj.CommonLib.Base;

namespace Production.ApplicationLib.Command
{
    public class CreateProcessCommand : ProcessEditRequestDto, IRequest<Result<ProcessInfoResponseDto>>
    {
    }

    public class CreateProcessCommandHandler : IRequestHandler<CreateProcessCommand, Result<ProcessInfoResponseDto>>
    {
        private readonly IProcessRepository _processRepository;
        private readonly IMapper _mapper;

        public CreateProcessCommandHandler(IProcessRepository processRepository,
            IMapper mapper)
        {
            _processRepository = processRepository;
            _mapper = mapper;
        }

        public async Task<Result<ProcessInfoResponseDto>> Handle(CreateProcessCommand request, CancellationToken cancellationToken)
        {
            var process = new Process(request.Code, request.Name, request.ProcessCategoryId,
                request.Description, request.ScheduleSort, request.ReferenceProcess, request.ScheduleType);
            _processRepository.Add(process);

            await _processRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<ProcessInfoResponseDto>.SuccessAsync(
                _mapper.Map<ProcessInfoResponseDto>(process));
        }
    }
}